/*
 * Copyright (c) 2006-2021, Ulandlink Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-09-18     lfz         first version
 */
#include <rtthread.h>
#include "drv_beep.h"

#ifdef ENABLE_PASSIVE_BUZSER
#ifdef RT_USING_PWM
#include <rt_drv_pwm.h>
#define BEEP_FREQ			(2700)  //2700Hz
struct rt_device_pwm     *pwm_device = RT_NULL;     //定义 pwm 设备指针

bool beep_set(uint32_t freq)
{
	rt_uint64_t period, pulse;  
	rt_err_t result = RT_EOK;
	period = 1000000000ULL / freq;  															//unit:ns 1/HZ*10^9 = ns		/* 将频率转化为周期 周期单位:ns 频率单位:HZ */
	pulse  = period >> 1;																		/* PWM占空 duty cycle =  (pulse / period) * 100 */
	result = rt_pwm_set(pwm_device, BEEP_PWM_CH, period, pulse);								/* 利用 PWM API 设定 周期和占空比 */
	return (result == RT_EOK ? true : false);
}

int32_t beep_init(void)
{
	pwm_device = (struct rt_device_pwm *)rt_device_find(BEEP_PWM_DEVICE);		/* 查找PWM设备 */
	if (pwm_device == RT_NULL){
		return -1;
	}
	if (!beep_set(BEEP_FREQ)){
		return -1;
	}  
	return 0;
}
#endif  /* RT_USING_PWM */
#endif  /* ENABLE_PASSIVE_BUZSER */

void beep_on(void)
{
#ifdef ENABLE_PASSIVE_BUZSER
	rt_pwm_enable(pwm_device, BEEP_PWM_CH); //使能蜂鸣器对应的 PWM 通道
#else
    rt_pin_write(BUZZER_PIN, PIN_HIGH); 
#endif
}

void beep_off(void)
{  
#ifdef ENABLE_PASSIVE_BUZSER
	rt_pwm_disable(pwm_device, BEEP_PWM_CH); //失能蜂鸣器对应的 PWM 通道
#else
    rt_pin_write(BUZZER_PIN, PIN_LOW); 
#endif
}



